package com.loe.camera;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.Html;
import android.util.Log;
import android.view.View;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.PermissionChecker;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;

public class PermissionUtil
{
    private static final String TAG = "PermissionUtil";

    public static List<String> STORAGE = Arrays.asList(Manifest.permission.READ_EXTERNAL_STORAGE);

    public static List<String> CAMERA = Arrays.asList(Manifest.permission.CAMERA);

    public static List<String> RECORD = Arrays.asList(Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO);

    public interface OnPermissionCallback
    {
        void onOk();

        void onError();
    }

    private static List<String> permission;

    private static String permissionName;

    public static void request(Activity activity, List<String> permission, OnPermissionCallback callback)
    {
        PermissionUtil.permission = permission;
        if (permission == STORAGE)
        {
            permissionName = "存储";
        }
        else if (permission == CAMERA)
        {
            permissionName = "相机";
        }
        else if (permission == RECORD)
        {
            permissionName = "相机和录音";
        }

        if (activity instanceof FragmentActivity)
        {
            if (permission == null || permission.isEmpty())
            {
                callback.onOk();
                return;
            }
            ArrayList<String> deniedPermissions = getDeniedPermissions(activity, permission);
            if (deniedPermissions.isEmpty())
            {
                callback.onOk();
                return;
            }
            FragmentManager manager = ((FragmentActivity) activity).getSupportFragmentManager();
            PermissionFragment fragment = (PermissionFragment) manager.findFragmentByTag(TAG);
            if (fragment == null)
            {
                fragment = new PermissionFragment();
                manager.beginTransaction().add(fragment, TAG).commitNowAllowingStateLoss();
            }
            fragment.callback = callback;
            fragment.requestPermissions(deniedPermissions.toArray(new String[0]), 15);
        }
        else
        {
            Log.e("Runtime-$TAG", "请传入FragmentActivity");
        }
    }

    public static void requestTip(Activity activity, String tip, List<String> permission, OnPermissionCallback callback)
    {
        // 限制提示
        if (!isTip())
        {
            request(activity, permission, callback);
            return;
        }

        PermissionUtil.permission = permission;
        if (permission == STORAGE)
        {
            permissionName = "存储";
            if (tip == null || tip.isEmpty())
            {
                tip = "为方便您访问或修改本地文件，请允许我们访问存储权限。";
            }
        }
        else if (permission == CAMERA)
        {
            permissionName = "相机";
            if (tip == null || tip.isEmpty())
            {
                tip = "为方便您拍摄照片，以及进行业务资料的上传，请允许我们访问摄像头。";
            }
        }
        else if (permission == RECORD)
        {
            permissionName = "相机和录音";
            if (tip == null || tip.isEmpty())
            {
                tip = "为方便您拍摄视频，以及进行业务资料的上传，请允许我们访问摄像头和麦克风。";
            }
        }

        if (tip == null || tip.isEmpty())
        {
            request(activity, permission, callback);
            return;
        }

        final OnPermissionCallback permissionCallback = callback;

        if (activity instanceof FragmentActivity)
        {
            final FragmentActivity fragmentActivity = (FragmentActivity) activity;
            if (permission == null || permission.isEmpty())
            {
                callback.onOk();
                return;
            }
            final ArrayList<String> deniedPermissions = getDeniedPermissions(activity, permission);
            if (deniedPermissions.isEmpty())
            {
                callback.onOk();
                return;
            }

            new PermissionTipDialog(fragmentActivity).okCallback(new LoeCamera.Callback()
            {
                @Override
                public void callback()
                {
                    FragmentManager manager = fragmentActivity.getSupportFragmentManager();
                    PermissionFragment fragment = (PermissionFragment) manager.findFragmentByTag(TAG);
                    if (fragment == null)
                    {
                        fragment = new PermissionFragment();
                        manager.beginTransaction().add(fragment, TAG).commitNowAllowingStateLoss();
                    }
                    fragment.callback = permissionCallback;
                    fragment.requestPermissions(deniedPermissions.toArray(new String[0]), 15);
                }
            }).cancelCallback(new LoeCamera.Callback()
            {
                @Override
                public void callback()
                {
                    permissionCallback.onError();
                }
            }).tip(tip).show();
        }
        else
        {
            Log.e("Runtime-$TAG", "请传入FragmentActivity");
        }
    }

    private static ArrayList getDeniedPermissions(Activity activity, List<String> permissions)
    {
        ArrayList list = new ArrayList<String>();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && activity.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.M)
        {
            for (String permission : permissions)
            {
                if (activity.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED)
                {
                    list.add(permission);
                }
            }
        }
        if (list.isEmpty())
        {
            for (String permission : permissions)
            {
                if (PermissionChecker.checkSelfPermission(activity, permission) != PermissionChecker.PERMISSION_GRANTED)
                {
                    list.add(permission);
                }
            }
        }
        return list;
    }

    public static class PermissionFragment extends Fragment
    {
        OnPermissionCallback callback;

        private void onCancel()
        {
            AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
            builder.setTitle("缺少“" + permissionName + "”权限");
            builder.setMessage(Html.fromHtml("<font color='#777777'>请点击 \"设置\"-\"权限\" 打开" + permissionName + "权限，点击两次后退按钮即可返回。</font>"));
            builder.setCancelable(false);
            builder.setPositiveButton("设置", null);
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialogInterface, int i)
                {
                    if (callback != null)
                    {
                        callback.onError();
                        callback = null;
                    }
                    dialogInterface.dismiss();
                }
            });
            final AlertDialog dialog = builder.create();
            dialog.show();
            dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View view)
                {
                    startAppSettings(getActivity(), new CameraResultUtil.OnActivityResultListener()
                    {
                        @Override
                        public void onActivityResult(int resultCode, Intent data)
                        {
                            if (isPermissionOk(getActivity(), permission))
                            {
                                dialog.dismiss();
                                if (callback != null)
                                {
                                    callback.onOk();
                                    callback = null;
                                }
                            }
                        }
                    });
                }
            });
            dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(Color.parseColor("#888888"));
            dialog.getButton(DialogInterface.BUTTON_POSITIVE).setTextColor(Color.parseColor("#5084fe"));
        }

        @Override
        public void onCreate(@Nullable Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setRetainInstance(true);
        }

        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
        {
            if (requestCode != 15 || callback == null)
            {
                return;
            }

            // android 10
            if (isPermissionOk(getActivity(), Arrays.asList(permissions)))
            {
                callback.onOk();
                callback = null;
            }
            else
            {
                onCancel();
            }
        }
    }

    /**
     * 判断权限是否完善
     */
    public static boolean isPermissionOk(Context context, List<String> permissions)
    {
        for (String permission : permissions)
        {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            {
                if (context.checkSelfPermission(permission) == PackageManager.PERMISSION_DENIED)
                {
                    return false;
                }
            }
            if (PermissionChecker.checkSelfPermission(context, permission) != PermissionChecker.PERMISSION_GRANTED)
            {
                return false;
            }
        }
        return true;
    }

    /**
     * 启动应用的设置
     */
    public static void startAppSettings(Activity activity, CameraResultUtil.OnActivityResultListener listener)
    {
        try
        {
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.setData(Uri.parse("package:" + activity.getPackageName()));
            CameraResultUtil.startResult((FragmentActivity) activity, intent, listener);
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    private static boolean isTip()
    {
        String cc = (Build.MANUFACTURER + "").toLowerCase();
        return cc.contains("huawei") || cc.contains("honor") || cc.contains("oce") || cc.contains("vivo") || cc.contains("iqoo");
    }
}